using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using StupidSpaceThing;

namespace RacerGame
{
	internal class Scorpion : Unit
	{
		public static new int _ProductionCost = 1000;
		public static new int _ProductionTime = 6000;
		public override int ProductionTime { get { return _ProductionTime; } }
		public override int ProductionCost { get { return _ProductionCost; } }
		private const int cooldownTime = 10;
		private int lastShot = 0;
		private Map.Cell nextCell;
		
		public Scorpion(Vector3 position)
			: base(new ScorpionEntity(position)) {
			massModifier = 30;			
		}

		public override void Update(RealGameTime gameTime) {			
			if( Entered ) {				
				if( Target != null ) {
					Vector2 force = Vector2.Normalize(Target.Position2D - Position2D) * 20;
					ApplyForce(force, false);
					Entity.ColObject.UpdateEntityPosition();
					Entity.RotateTowards(Position + new Vector3(lastForce.X, 0, lastForce.Y));
				}
				// optimize
				FactionEntity target = null;
				float targetDistance = float.MaxValue;
				foreach( Faction faction in Faction.Factions ) {
					if( faction == Faction ) continue;
					foreach( FactionEntity fe in faction.FactionEntities ) {
						if( faction == Faction.None && fe is Structure ) continue;
						float curDistance = Vector3.Distance(Position, fe.Position);
						if( target == null || curDistance < targetDistance ) {
							target = fe;
							targetDistance = curDistance;
							/*Vector2? col = Game1.CurMap.CheckCollision(Position2D, fe.Position2D);
							if( col == null ) {
								target = fe;
								targetDistance = curDistance;
							}*/					
						}
					}
				}				
				Target = target;
				if( targetDistance < 45 ) {
					if( lastShot == 0 ) {
						//Bullets.FirePredict(gameTime, this, Target, 0.0f);
						RacerGame.PlayCue("shot_enemy", RacerGame.Listener, AudioEmitter);
						for( int i = 0; i < 2; i++ ) {
							Bullets.Fire(Faction.Color, this, Target, 0, gameTime);
						}
						lastShot++;
					} else {
						lastShot++;
						if( lastShot > cooldownTime ) {
							lastShot = 0;
						}
					}
				}
			}
			base.Update(gameTime);
		}
	}
}
